//
//  LJUserAccount.swift
//  LJWeibo
//
//  Created by 连俊杨 on 2017/10/20.
//  Copyright © 2017年 yang_ljun. All rights reserved.
//

import UIKit
private let userAccountInfo: NSString = "userAccountInfo.json"

/// 用户信息模型
class LJUserAccount: NSObject {

    var access_token: String?
    
    var uid: String?
    
    /// 过期时间  开发者5年、使用者3天
    var expires_in: TimeInterval = 0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// 过期日期
    var expiresDate: Date?
    
    /// 用户信息
    var screen_name: String?
    var avatar_large: String?
    
    override var description: String {
        return yy_modelDescription()
    }
    
    /// 用户信息的构造方法
    override init() {
        super.init()
        /// 1.从沙盒取数据
        guard let filePath = userAccountInfo.cz_appendDocumentDir(),
            let data = NSData(contentsOfFile: filePath),
            let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: AnyObject] else {
                return
        }
        
        /// 2.设置给当前账户
        self.yy_modelSet(with: dict ?? [:])
        
        /// 测试token过期
        /// expiresDate = Date(timeIntervalSinceNow: -3600*24)
        
        /// 3.token过期处理
        if expiresDate?.compare(Date()) != .orderedDescending { /// 过期了
            access_token = nil
            uid = nil
            
            _ = try? FileManager.default.removeItem(atPath: filePath)
        }
    }
    
    func saveUserAccount() {
        /// 1.模型转字典
        var dict = self.yy_modelToJSONObject() as? [String: AnyObject] ?? [:]
        /// 2.去除expires_in字段
        _ = dict.removeValue(forKey: "expires_in")
        
        /// 3.写入磁盘
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
            let filePath = userAccountInfo.cz_appendDocumentDir() else {
                return
        }
        (data as NSData).write(toFile: filePath, atomically: true)
        print("保存成功\(filePath)")    
    }
}




